package com.example.administrator.szb.activity;

import android.app.AlertDialog;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.example.administrator.szb.R;
import com.example.administrator.szb.bean.RzBean;
import com.example.administrator.szb.bean.UserEditBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.ChangeStatuUtil;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.Toasts;
import com.example.zhouwei.library.CustomPopWindow;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import dmax.dialog.SpotsDialog;


/**
 * Created by D N on 2017/9/26.
 * 用户编辑资料
 */

public class UserEditActivity extends TakePhotoActivity {
    @Bind(R.id.useredit_image_icon)
    CircleImageView usereditImageIcon;
    @Bind(R.id.useredit_text_bc)
    TextView usereditTextBc;
    @Bind(R.id.toolbar9)
    Toolbar toolbar9;
    @Bind(R.id.useredit_edit_nc)
    EditText usereditEditNc;
    @Bind(R.id.useredit_text_nc)
    TextView usereditTextNc;
    @Bind(R.id.textView55)
    TextView textView55;
    @Bind(R.id.useredit_text_ms)
    TextView usereditTextMs;
    @Bind(R.id.useredit_edit_ms)
    EditText usereditEditMs;
    @Bind(R.id.textView61)
    TextView textView61;
    @Bind(R.id.textView62)
    TextView textView62;
    @Bind(R.id.useredit_image_addMP)
    ImageView usereditImageAddMP;

    InputMethodManager imm;//软键盘
    CustomPopWindow popWindow;//弹出框
    TakePhoto take = getTakePhoto();
    protected Uri imageUri;
    String iconPath = "";//从相机或相册中获取的图片路径
    String mpPath = "";
    @Bind(R.id.useredit_image_fh)
    ImageView usereditImageFh;
    private int who = 0;//0代表头像，1代表名片

    ArrayList<String> useredit_info = new ArrayList<String>();//存放用户填入的信息
    AlertDialog dialog;//进度条

    UserEditBean userEditBean;
    public interface isRefresh{
        void doSomeThing(int is_fresh);//1,刷新
    }

    public static isRefresh isRefresh;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_edit_activity);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        SampleApplicationLike.getActivitiesInstance().add(this);

        imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);//软键盘实例
        ButterKnife.bind(this);



        requestUserInfo();
    }

    private void requestUserInfo() {
        HashMap<String,String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("users_id",SampleApplicationLike.getUserloginInstance().getId()+"");
        String url = URLAddress.URLBASE + URLAddress.URL_USE_INFO;
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, UserEditBean.class, url, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                userEditBean = (UserEditBean) response;
                if (userEditBean.getResult() == 1){
                    initView();
                }else{
                    Toasts.show(UserEditActivity.this, ""+userEditBean.getErr_msg(), Toast.LENGTH_SHORT);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toasts.show(UserEditActivity.this, "网络异常", Toast.LENGTH_SHORT);
            }
        });
    }

    private void initView() {
        if (!TextUtils.isEmpty(userEditBean.getData().getHeadimg())){
            Glide.with(UserEditActivity.this).load(userEditBean.getData().getHeadimg()).error(R.drawable.mrtx).into(usereditImageIcon);
        }
        if (!TextUtils.isEmpty(userEditBean.getData().getNick_name())){
            usereditEditNc.setText(userEditBean.getData().getNick_name());
        }

        if (!TextUtils.isEmpty(userEditBean.getData().getSketch())){
            usereditEditMs.setText(userEditBean.getData().getSketch());
        }

        if (!TextUtils.isEmpty(userEditBean.getData().getBusiness())){
            Glide.with(UserEditActivity.this).load(userEditBean.getData().getHeadimg()).error(R.drawable.add_id_image).into(usereditImageAddMP);
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @OnClick({R.id.useredit_image_icon, R.id.useredit_text_bc, R.id.useredit_image_addMP,R.id.useredit_image_fh})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.useredit_image_icon:
                who = 0;
                if (imm.isActive() && getCurrentFocus() != null) {
                    if (getCurrentFocus().getWindowToken() != null) {
                        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
                showPopupwindow(R.layout.view_popupwindow_picture_choose, R.layout.user_edit_activity);
                break;
            case R.id.useredit_text_bc:
                requestSava();//保存操作
                break;
            case R.id.useredit_image_addMP:
                who = 1;
                if (imm.isActive() && getCurrentFocus() != null) {
                    if (getCurrentFocus().getWindowToken() != null) {
                        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
                showPopupwindow(R.layout.view_popupwindow_picture_choose, R.layout.user_edit_activity);
                break;
            case R.id.useredit_image_fh:
                finish();
                break;
        }
    }

    private void requestSava() {
        boolean flag = checkInfo();//检查用户信息是否完整；
        if (flag) {
            doRequestSava();
        }
    }

    /**
     * 执行保存资料请求
     */
    private void doRequestSava() {
        showProgressbar();//显示进度条
        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("id", SampleApplicationLike.getUserloginInstance().getId() + "");

        map.put("nick_name", useredit_info.get(1));
        if (TextUtils.isEmpty(useredit_info.get(2))) {
            map.put("sketch", "赶紧给自己加一句签名吧。。。");
        } else {
            map.put("sketch", useredit_info.get(2));
        }
        try {
            map.put("headimg", ChangeStatuUtil.bitmapToString(iconPath));
            map.put("business", ChangeStatuUtil.bitmapToString(mpPath));
        }catch (Exception e){
            map.put("headimg", "0");
            map.put("business", "0");
        }

        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, RzBean.class, URLAddress.URLBASE + URLAddress.URL_AU, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                RzBean rzBean = (RzBean) response;
                if (rzBean.getResult() != 1) {
                    dialog.dismiss();

                    DialogUtil.showSimpleDialog(UserEditActivity.this, rzBean.getErr_msg());
                } else {
                    //FragmentMy.requestUserData();

                    isRefresh.doSomeThing(1);
                    dialog.dismiss();
                    finish();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.toString();
            }
        });
    }

    /**
     * 显示进度条
     */
    private void showProgressbar() {
        dialog = new SpotsDialog(this, R.style.Custom);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        // WindowManager m = getWindowManager();
//        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
//        android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
//        p.height = 300;   //高度设置为屏幕的0.3
//        p.width = 500;    //宽度设置为屏幕的0.5
//        dialog.getWindow().setAttributes(p);
    }

    /**
     * 检查信息
     *
     * @return
     */
    private boolean checkInfo() {
        getInfo();//first get write info.
        if (TextUtils.isEmpty(useredit_info.get(0))) {
            DialogUtil.showSimpleDialog(UserEditActivity.this, "请添加头像");
        } else if (TextUtils.isEmpty(useredit_info.get(1))) {
            DialogUtil.showSimpleDialog(UserEditActivity.this, "请输入昵称");
        } else if (TextUtils.isEmpty(useredit_info.get(3))) {
            DialogUtil.showSimpleDialog(UserEditActivity.this, "请选择上传的名片");
        } else {
            return true;
        }

        return false;
    }

    /**
     * 获取填入的信息
     */
    private void getInfo() {
        useredit_info.clear();
        if (usereditImageIcon.getDrawable().getCurrent().getConstantState() == getResources().getDrawable(R.drawable.mrtx).getConstantState()) {//判断是不是默认图片
            useredit_info.add(null);
        } else {
            // String image_buff = new String(getImageBytes(getBitmapFromPath(iconPath)));
            useredit_info.add("has data");
        }
        useredit_info.add(usereditEditNc.getText().toString().trim());
        useredit_info.add(usereditEditMs.getText().toString().trim());

        if (usereditImageAddMP.getDrawable().getCurrent().getConstantState() == getResources().getDrawable(R.drawable.add_id_image).getConstantState()) {//判断是不是默认图片
            useredit_info.add(null);
        } else {
            // String image_buff = new String(getImageBytes(getBitmapFromPath(iconPath)));
            useredit_info.add("has data");
        }


    }


    /**
     * 初始化popupwindow弹出框
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void showPopupwindow(int view_layout_id, int rootview_layout_id) {
        View popwindow_view = LayoutInflater.from(this).inflate(view_layout_id, null);
        View rootview = LayoutInflater.from(this).inflate(rootview_layout_id, null);

        //如果不是进度框，就执行底部弹出

        popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(popwindow_view)//显示的布局，还可以通过设置一个View
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) //设置显示的大小，不设置就默认包裹内容
                .setFocusable(true)//是否获取焦点，默认为ture
                .setOutsideTouchable(true)//是否PopupWindow 以外触摸dissmiss
                .create()//创建PopupWindow
                .showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        handleLogic(popwindow_view, popWindow);//处理popupwindow 中的item点击事件

        //显示PopupWindow

    }

    /**
     * 处理弹出显示内容、点击事件等逻辑
     *
     * @param contentView
     */
    private void handleLogic(View contentView, final CustomPopWindow mCustomPopWindow) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCustomPopWindow != null) {
                    mCustomPopWindow.dissmiss();
                }
                String showContent = "";
                switch (v.getId()) {
                    case R.id.textView26:
                        takePhoto();
                        break;
                    case R.id.textView27:
                        // showContent = "点击 Item菜单2";
                        chooseImage();
                        break;
                    case R.id.textView28:
                        mCustomPopWindow.dissmiss();
                        break;
                }
                //Toasts.show(MingPianActivity.this, showContent, Toast.LENGTH_SHORT);
            }
        };
        contentView.findViewById(R.id.textView26).setOnClickListener(listener);
        contentView.findViewById(R.id.textView27).setOnClickListener(listener);
        contentView.findViewById(R.id.textView28).setOnClickListener(listener);

    }

    /**
     * 开启相机拍照
     */
    public void takePhoto() {
        //take.onPickFromCapture(getImageUri());//执行拍照
        CropOptions cropOptions=new CropOptions.Builder().setAspectX(9999).setAspectY(9998).setWithOwnCrop(false).create();
        take.onPickFromCaptureWithCrop(getImageUri(),cropOptions);
    }

    /**
     * 返回一个Uri给take调用
     */
    public Uri getImageUri() {
        File file = getImgFile();
        imageUri = Uri.fromFile(file);
        return imageUri;

    }

    /**
     * 设置文件存储路径，返回一个file
     *
     * @return
     */
    private File getImgFile() {
        File file = new File(Environment.getExternalStorageDirectory() + "/szb/image");
        if (!file.exists()) {
            //要点！
            file.mkdirs();
        }
        File imgFile = new File(file, "image" + System.currentTimeMillis() + ".jpg");
        return imgFile;

    }

    /**
     * 开启图片选择
     */
    private void chooseImage() {
        //take.onPickFromGallery();
        CropOptions cropOptions=new CropOptions.Builder().setAspectX(9999).setAspectY(9998).setWithOwnCrop(false).create();
        take.onPickFromGalleryWithCrop(getImageUri(),cropOptions);
    }

    /**
     * 拍照或者从相片选取相片的回调方法
     *
     * @param result
     */
    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);

        if (who == 0) {
            iconPath = result.getImage().getOriginalPath();
            Glide.with(this).load(new File(iconPath)).into(usereditImageIcon);
        } else if (who == 1) {
            mpPath = result.getImage().getOriginalPath();
            Glide.with(this).load(new File(mpPath)).into(usereditImageAddMP);
        }

    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }
}
